package com.example.carrierapp.ui.login;

import com.example.carrierapp.base.BasePresenter;
import com.example.carrierapp.common.CarrierApplication;
import com.example.carrierapp.config.ConstValue;
import com.example.carrierapp.net.ApiMiddleHelper;
import com.example.carrierapp.net.listener.DataCallBackListener;
import com.example.carrierapp.util.LogUtil;
import com.example.carrierapp.util.SPUtils;
import com.google.gson.JsonObject;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

import io.reactivex.Flowable;

public class LoginPresenter extends BasePresenter<LoginContract.View> implements LoginContract.Presenter {
    public LoginPresenter() {
    }

    @Override
    public void start() {

    }

    @Override
    public void login(String name, String pass) {
        Map<String, String> biddingMap = new HashMap<>();
        biddingMap.put("username", name);
        biddingMap.put("password", pass);
        Flowable<JsonObject> flowable = apiStrores.login(biddingMap);
        ApiMiddleHelper.getInstance().toNetIo2Main(null,flowable, new DataCallBackListener() {
            @Override
            public void onSuccess(String json) {
                LogUtil.i("TAG", "login-" + json);
                LogUtil.d("login-onSuccess-" + json);
                try {

                    JSONObject object = new JSONObject(json);

                    SPUtils.putString(CarrierApplication.mAppContext, ConstValue.URL_TOKEN, object.getString("key"));
                    SPUtils.putString(CarrierApplication.mAppContext, ConstValue.LOGIN_COUNT, name);
                    SPUtils.putString(CarrierApplication.mAppContext, ConstValue.LOGIN_PASS, pass);
                    SPUtils.putBoolean(CarrierApplication.mAppContext, ConstValue.LOGIN_STATE, true);
                    if (getView() != null) {
                        getView().loginSuccess("");
                    }
                } catch (JSONException e) {
                    onFailure("数据解析错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String msg) {
                SPUtils.putBoolean(CarrierApplication.mAppContext, ConstValue.LOGIN_STATE, false);
                LogUtil.d("login-onFailure-" + msg);
                if (getView() != null) {
                    getView().loginFailde(msg);
                }
            }
        });
    }
}
